// src/shared/header/index.tsx
import React from "react";
import styles from "./index.module.css";
import { connect, MapDispatchToPropsParam, MapStateToPropsParam } from "react-redux";
import { AppState, AppThunkDispatch } from "@src/index";
import { UserCreators } from "@store/creators/UserCreators";
import { UserActions } from "@actions/userActions";
import { UserState } from "@reducers/userReducer";
import Confirm from "@shared/confirm";
import { history } from "@src/App";
interface StateProps {
    userReducer: UserState;
}
interface DispatchProps {
    requestUserInfo: () => Promise<UserActions.Actions>;
    // 清空用户信息
    clearUser: () => UserActions.ClearUser;
}
interface OwnProps { }
//组件类型
interface States {
    // 控制退出登录弹窗是否渲染
    isOpen: boolean;
}
// 组件 Props 对象的最终类型
type Props = StateProps & DispatchProps & OwnProps;



class Header extends React.Component<Props, States> {
    state = {
        // 控制退出登录弹窗是否渲染
        isOpen: false,
    };
    async componentDidMount() {
        await this.props.requestUserInfo()
    }
    userInfo() {
        const { userReducer, clearUser } = this.props
        if (userReducer.user.status !== 'success') return
        console.log(this.state.isOpen)
        return (

            <>
                <span>{userReducer.user.result.name}</span>
                <button className="button is-ghost has-text-white" onClick={() => this.setState({ isOpen: true })}>退出</button>
                <Confirm isOpen={this.state.isOpen} close={() => this.setState({ isOpen: false })} onSureButtonClicked={() => {
                    // 清空用户信息
                    clearUser();
                    // 跳转到登录页
                    history.replace("/login");

                }}
                    onCancelButtonClicked={() => {
                        this.setState({ isOpen: false })
                    }}
                >
                    您确定要退出登录吗?
                </Confirm>
            </>

        )
    }
    render() {
        return (
            <div className={styles.header}>
                <div className={styles.logo}>
                    <img src={require("@image/logo.png")} alt="极客园" />
                </div>

                <div className={styles.user}>
                    {this.userInfo()}
                </div>
            </div>
        );
    }
}


const mapStateToProps: MapStateToPropsParam<StateProps, OwnProps, AppState> = (state) => ({
    userReducer: state.userReducer
})
const mapDispatchToProps: MapDispatchToPropsParam<DispatchProps, OwnProps> = (dispatch: AppThunkDispatch) => ({
    // 获取用户信息
    requestUserInfo: () => dispatch(UserCreators.requestUserInfo()),
    // 清空用户信息
    clearUser: () => dispatch(UserCreators.clearUser()),
});
export default connect(mapStateToProps, mapDispatchToProps)(Header)